package leet;

/**
 * 566. Reshape the Matrix
 * 
 * <pre>
 * In MATLAB, there is a very useful function called 'reshape', which can
 * reshape a matrix into a new one with different size but keep its original
 * data.
 * 
 * You're given a matrix represented by a two-dimensional array, and two
 * positive integers r and c representing the row number and column number of
 * the wanted reshaped matrix, respectively.
 * 
 * The reshaped matrix need to be filled with all the elements of the original
 * matrix in the same row-traversing order as they were.
 * 
 * If the 'reshape' operation with given parameters is possible and legal,
 * output the new reshaped matrix; Otherwise, output the original matrix.
 * </pre>
 * 
 * @author zhujunbing
 * @date 2019年4月25日
 */
public class Leet0566 {

	public static void main(String[] args) {
		Leet0566 leet0566 = new Leet0566();
		int[][] nums = { { 1, 2 }, { 3, 4 } };
		int r = 1;
		int c = 4;
		int[][] matrixReshape = leet0566.matrixReshape(nums, r, c);

		for (int[] is : matrixReshape) {
			System.out.print("[");
			for (int i : is) {
				System.out.print(i);
			}
			System.out.println("]");
		}

	}

	/**
	 * 1ms
	 * 
	 * @param nums
	 * @param r
	 * @param c
	 * @return
	 * @date 2019年4月25日
	 */
	public int[][] matrixReshape(int[][] nums, int r, int c) {

		if (nums.length * nums[0].length != r * c) {
			return nums;
		}

		int[][] ret = new int[r][c];

		int l = nums[0].length;

		for (int i = 0; i < nums.length; i++) {

			for (int j = 0; j < l; j++) {
				ret[(i * l + j) / c][(i * l + j) % c] = nums[i][j];
			}

		}

		return ret;
	}

}
